#include "sql_parser.h"

void SQLParser::Parse(const string& line, string& command, 
					  map<string, string>& args)
{
  string lowercaseline = line;
  /*  if (line[line.length()-1] != ';')
	{
	  cerr<<"command not end with ;";
      cout<<line<<endl;
	  return;
      }*/                       // execute does not end with ;
  BasicTool::ToLowercase(lowercaseline);
  command = lowercaseline.substr(0, lowercaseline.find_first_of(" ;"));
  if (command == "select")
	{
		  string::size_type i = lowercaseline.find('=');
		  if (i == string::npos)
			{
			  cerr<<"invalid query"<<endl;
			  return;
			}
		  string::size_type il = lowercaseline.find_last_not_of(' ', i-1);
		  string::size_type j = lowercaseline.rfind(' ', il); // no space inside field
		  
		  string fieldname = lowercaseline.substr(j+1, il-j);

		  string valuename;
		  string::size_type ir = lowercaseline.find_first_not_of(' ', i+1);
		  if (lowercaseline[ir] == '\"')
			{
			  string::size_type j = lowercaseline.find('\"', ir+1);
			  while (j != string::npos && lowercaseline[j-1] == '\\')
				{
				  j = lowercaseline.find('\"', j+1);
				}
			  if (j == string::npos)
				{
				  cerr<<"no corresponding \""<<endl;
				  return;
				}
			  valuename = lowercaseline.substr(ir+1, j-ir-1);
			}
		  else if (lowercaseline[ir] == '\'')
			{
			  string::size_type j = lowercaseline.find('\'', ir+1);
			  while (j != string::npos && lowercaseline[j-1] == '\\')
				{
				  j = lowercaseline.find('\'', j+1);
				}
			  if (j == string::npos)
				{
				  cerr<<"no corresponding \'"<<endl;
				  return;
				}
			  valuename = lowercaseline.substr(ir+1, j-ir-1);
			}
		  else
			{
			  string::size_type j = lowercaseline.find_first_of(" ;", ir);
			  if (j == string::npos)
				{
				  cerr<<"no space"<<endl;
				  return;
				}
			  valuename = lowercaseline.substr(ir, j-ir);
			}

		  string strAtVal = fieldname + "=\"" + valuename+"\"";;
		  args["strAtVal"] = strAtVal;
		  
		  // look for offset
		  i = lowercaseline.find("offset");
		  if (i == string::npos)
			{
			  args["strOffset"] = "-1";
			}
		  else
			{
			  j = lowercaseline.find(' ', i);
			  i = lowercaseline.find_first_of(" ;", j+1);
			  string offset = lowercaseline.substr(j+1, i-j-1);
			  args["strOffset"] = offset;
			}
		  // look for limit
		  i = lowercaseline.find("limit");
		  if (i == string::npos)
			{
			  args["strLimit"] = "-1";
			}
		  else
			{
			  j = lowercaseline.find(' ', i);
			  i = lowercaseline.find_first_of(" ;", j+1);
			  string limit = lowercaseline.substr(j+1, i-j-1);
			  args["strLimit"] = limit;
			}
	}
}
